import router, { constantRouterMap } from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, getPermission } from './auth.js'
import { filterRoutes } from './filterRoutes'
import store from './store'
const whiteList = ['/index', '/auth-redirect'] // no redirect whitelist
var getRouter = [] //用来获取后台拿到的路由
var publicRouter = constantRouterMap
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  next()
  if (getToken()) {
    if (to.path === '/index') {
      // next();
      next({
        path: '/',
      })
      NProgress.done()
    } else {
      if (getRouter.length == 0) {
        if (getObjArr('router') === 0 || getObjArr('router') == null) {
          //权限路由
          getRouter = getPermission()
          saveObjArr('router', getRouter) //存储路由到sessionStorage
          routerGo(to, from, next) //执行路由跳转方法
        } else {
          //存储路由后，记录上个账号登录router,下个账号不能获取router
          getRouter = getObjArr('router') //拿到路由

          routerGo(to, from, next)
        }
      } else {
        //点击路由跳转 按钮权限
        getBtnPermission(to)
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/index`)
      NProgress.done()
    }
  }
})

function routerGo(to, from, next) {
  getRouter = filterRoutes(getRouter) //过滤路由

  global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
  for (var i = 0; i < publicRouter.length; i++) {
    global.antRouter.push(publicRouter[i])
  }
  getBtnPermission(to)
  router.addRoutes(getRouter)
  next({
    ...to,
    replace: true,
  })
}

function saveObjArr(name, data) {
  //sessionStorage 存储数组对象的方法s
  sessionStorage.setItem(name, JSON.stringify(data))
}

function getObjArr(name) {
  //sessionStorage 获取数组对象的方法
  return JSON.parse(window.sessionStorage.getItem(name))
}
// 取按钮权限
function getBtnPermission(to) {
  if (to.meta && to.meta.identifying) {
    let string = to.meta.identifying.substring(
      0,
      to.meta.identifying.length - 1
    )
    let arr = string.split(',') || []
    store.dispatch('setBtnPermission', arr)
  } else {
    store.dispatch('setBtnPermission', [])
  }
}
router.beforeResolve((to, from, next) => {
  next()
})
router.afterEach(() => {
  NProgress.done()
})
